package com.xiaode.controller.app.task.labour;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Redis;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.Admin;
import com.xiaode.common.model.KeyResultsTask;
import com.xiaode.common.model.LabourTask;
import com.xiaode.common.model.StudentTrajectory;
import com.xiaode.common.model.TaskLog;
import com.xiaode.common.model.VocationTask;
import com.xiaode.common.model.dto.task.KeyResultsDTO;
import com.xiaode.exce.EnumError;
import com.xiaode.util.UserUtil;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class LabourService {


	/**
     * 查询日常劳动
     */
    public Ret findLabourPage(Integer accountId, Integer accountIdMy, Integer page, Integer limit) throws Exception {

        Page<LabourTask> labourTaskPage = new Page<LabourTask>();
        if (accountId != null) {
            labourTaskPage = LabourTask.dao.paginate(page, limit, "SELECT *", "FROM labour_task WHERE user_account_id = ? AND evaluate_account_id IS NOT NULL ORDER BY id DESC", accountId);
        }else {
            labourTaskPage = LabourTask.dao.paginate(page, limit, "SELECT *", "FROM labour_task WHERE user_account_id = ? ORDER BY id DESC", accountIdMy);
        }
        for (LabourTask labour : labourTaskPage.getList()) {
            if (labour.getInt("evaluate_account_id") != null) {
                Integer teaAccountId = labour.getInt("evaluate_account_id");
                Record o = Redis.use().hget(Const.user.AccountIdInfo, teaAccountId);
                Admin admin = Redis.use().get(Const.user.Admin + o.getInt("id"));
                labour.put("teaName", admin.getName());
                labour.put("teaId", admin.getId());
                labour.put("teaAccountId", admin.getAccountId());
                labour.put("teaGender", admin.getGender());
                labour.put("teaPic", admin.getAvatarUrl());
            }
        }
        return Ret.ok("recordList", labourTaskPage);
    }

    /**
     * 提交日常劳动
     */
    @Before(Tx.class)
    public Ret commitLabourRecord(Integer accountId, String title, String content, String files) throws Exception {
        LabourTask labour = new LabourTask();
        labour.setContent(content);
        labour.setFiles(files);
        labour.setTitle(title);
        labour.setUserAccountId(accountId);
        labour.setState(Const.taskState.UNAUDITED);
        labour.save();
        //保存我的日常劳动记录
        TaskLog taskLog = new TaskLog();
        taskLog.setTaskType(Const.taskType.LABORU_TASK_TYPE);
        taskLog.setTaskState(Const.taskState.UNAUDITED);
        taskLog.setUserAccountId(accountId);
        taskLog.setTaskDate(LocalDateTime.now());
        taskLog.setTaskId(labour.getId());
        taskLog.save();
        
        return Ret.ok();
    }

    /**
     * 发表我的职业劳动
     */
    @Before(Tx.class)
    public Ret commitVocationLabour(Integer accountId, Integer studentId, Integer taskAlignmentId, String content, String keyResults, String files) throws Exception {
        //创建我的职业劳动
        VocationTask vocationLabour = new VocationTask();
        vocationLabour.setContent(content);
        vocationLabour.setState(Const.taskState.UNAUDITED);
        vocationLabour.setFiles(files);
        vocationLabour.setUserAccountId(accountId);
        if (taskAlignmentId != null) {
            //  处理任务对齐  查询任务对齐的内容 赋值   
        	String exampleTaskContent = Db.queryStr("SELECT content FROM student_example_task WHERE id = ? AND studentId = ?", taskAlignmentId, studentId);
            vocationLabour.setTaskAlignment(exampleTaskContent);
        }
        vocationLabour.save();
        
        //任务记录
        TaskLog taskLog = new TaskLog();
        taskLog.setTaskType(Const.taskType.VOCATION_TASK_TYPE);
        taskLog.setTaskDate(LocalDateTime.now());
        taskLog.setTaskState(Const.taskState.UNAUDITED);
        taskLog.setUserAccountId(accountId);
        taskLog.setTaskId(vocationLabour.getId());
        taskLog.save();
        
        //处理关键结果
        List<KeyResultsDTO> keyResultsDTOS = JSONUtil.toList(keyResults, KeyResultsDTO.class);
        ArrayList<KeyResultsTask> results = new ArrayList<>(keyResultsDTOS.size());
        //校验关键结果长度是否超过限制
        for (KeyResultsDTO keyResultsDTO : keyResultsDTOS) {
            String dtoContent = keyResultsDTO.getContent();
            if (dtoContent.length() > 200) {
                return Ret.fail().set("error", EnumError.KEY_RES_LENGTH_TOO_LONG.getObj());
            }
            if(dtoContent.length() > 0) {
            	KeyResultsTask res = new KeyResultsTask();
                res.setContent(dtoContent);
                res.setFiles(keyResultsDTO.getFiles());
                res.setTaskType(Const.taskType.VOCATION_TASK_TYPE);
                res.setTaskId(vocationLabour.getId());
                results.add(res);
            }
        }
        Db.batchSave(results, results.size());
        
        return Ret.ok();
    }

    /**
     * 查询我的职业劳动
     */
    public Ret findVocationLabourPage(Integer accountId, Integer accountIdMy, Integer page, Integer limit) throws Exception {
        Page<VocationTask> vocationTaskPage = new Page<VocationTask>();
        if(accountId != null){
            vocationTaskPage = VocationTask.dao.paginate(page, limit, "SELECT *", "FROM vocation_task WHERE user_account_id = ? AND evaluate_account_id IS NOT NULL ORDER BY id DESC", accountId);
        }else{
            vocationTaskPage = VocationTask.dao.paginate(page, limit, "SELECT *", "FROM vocation_task WHERE user_account_id = ? ORDER BY id DESC", accountIdMy);
        }
        for (VocationTask vocationTask : vocationTaskPage.getList()) {
        	//添加关键结果
        	List<KeyResultsTask> keyResultsTaskList = KeyResultsTask.dao.find("SELECT * FROM key_results_task WHERE task_id = ? AND task_type = ?", vocationTask.getId(), Const.taskType.VOCATION_TASK_TYPE);
        	vocationTask.put("keyResultsTaskList", keyResultsTaskList);
        	
        	//添加审核老师信息
            if (vocationTask.getInt("evaluate_account_id") != null) {
                Integer teaAccountId = vocationTask.getInt("evaluate_account_id");
                Record o = Redis.use().hget(Const.user.AccountIdInfo, teaAccountId);
                Admin admin = Redis.use().get(Const.user.Admin + o.getInt("id"));
                vocationTask.put("teaName", admin.getName());
                vocationTask.put("teaId", admin.getId());
                vocationTask.put("teaAccountId", admin.getAccountId());
                vocationTask.put("teaGender", admin.getGender());
                vocationTask.put("teaPic", admin.getAvatarUrl());
            }
        }
        return Ret.ok("vocationLabourPage", vocationTaskPage);
    }
    
    
    
    
    
    
    /**
     * 劳动任务审核
     */
    public Ret examineLabour(Integer accountId, Integer userType, Integer taskId, Integer score, String content, Boolean addTrajectory) throws Exception {
    	//如果当前用户不是教师
        if (userType != Const.UserType.admin) {
            return Ret.fail().set("error", EnumError.ALLOW_ADMIN_EXAMINE.getObj());
        }
        LabourTask labourTask = LabourTask.dao.findById(taskId);
        if (BeanUtil.isEmpty(labourTask)) {
            return Ret.fail().set("error", EnumError.TASK_NOT_EXIST.getObj());
        }
        if (labourTask.getState().intValue() == Const.taskState.REVIEWED) {
            return Ret.fail().set("error", EnumError.TASK_HAVA_EXAMINED.getObj());
        }
        //更新任务审核信息
        labourTask.setScoreTeacher(score);
        labourTask.setEvaluateTime(LocalDateTime.now());
        labourTask.setEvaluateContent(content);
        labourTask.setEvaluateAccountId(accountId);
        labourTask.setState(Const.taskState.REVIEWED);
        labourTask.setUpdateTime(LocalDateTime.now());
        labourTask.update();
        //跟新任务记录
        TaskLog taskLog = TaskLog.dao.findFirst("SELECT * FROM task_log WHERE task_id = ? AND task_type = ?", taskId, Const.taskType.LABORU_TASK_TYPE);
        taskLog.setTaskId(taskId);
        taskLog.setEvaluateAccountId(accountId);
        taskLog.setEvaluateTime(LocalDateTime.now());
        taskLog.setTaskState(Const.taskState.REVIEWED);
        taskLog.setUpdateTime(LocalDateTime.now());
        taskLog.update();
        //加入轨迹图
        if (score >= 3 && addTrajectory){
        	StudentTrajectory studentTrajectory = new StudentTrajectory();
            studentTrajectory.setTaskId(taskId);
            studentTrajectory.setTaskType(Const.taskType.LABORU_TASK_TYPE);
            studentTrajectory.setUserAccountId(labourTask.getUserAccountId());
            studentTrajectory.setContent(labourTask.getContent());
            studentTrajectory.save();
        }
        //给学生加分
        if (score > 0) {
            Record record = Redis.use().hget(Const.user.AccountIdInfo, labourTask.getUserAccountId());
            UserUtil.addScoreForStu(record.getInt("id"), score, Const.addMarkEventType.LABORU_TASK, labourTask.getId());
        }
        
        return Ret.ok();
    }
    
    /**
     * 职业体验任务审核
     */
    public Ret examineVocation(Integer accountId, Integer userType, Integer taskId, Integer score, String content, Boolean addTrajectory) throws Exception {
    	//如果当前用户不是教师
        if (userType != Const.UserType.admin) {
            return Ret.fail().set("error", EnumError.ALLOW_ADMIN_EXAMINE.getObj());
        }
        VocationTask vocationTask = VocationTask.dao.findById(taskId);
        if (BeanUtil.isEmpty(vocationTask)) {
            return Ret.fail().set("error", EnumError.TASK_NOT_EXIST.getObj());
        }
        if (vocationTask.getState().intValue() == Const.taskState.REVIEWED) {
            return Ret.fail().set("error", EnumError.TASK_HAVA_EXAMINED.getObj());
        }
        //更新任务审核信息
        vocationTask.setScoreTeacher(score);
        vocationTask.setEvaluateTime(LocalDateTime.now());
        vocationTask.setEvaluateContent(content);
        vocationTask.setEvaluateAccountId(accountId);
        vocationTask.setState(Const.taskState.REVIEWED);
        vocationTask.setUpdateTime(LocalDateTime.now());
        vocationTask.update();
        //跟新任务记录
        TaskLog taskLog = TaskLog.dao.findFirst("SELECT * FROM task_log WHERE task_id = ? AND task_type = ?", taskId, Const.taskType.VOCATION_TASK_TYPE);
        taskLog.setTaskId(taskId);
        taskLog.setEvaluateAccountId(accountId);
        taskLog.setEvaluateTime(LocalDateTime.now());
        taskLog.setTaskState(Const.taskState.REVIEWED);
        taskLog.setUpdateTime(LocalDateTime.now());
        taskLog.update();
        //加入轨迹图
        if (score >= 3 && addTrajectory){
        	StudentTrajectory studentTrajectory = new StudentTrajectory();
            studentTrajectory.setTaskId(taskId);
            studentTrajectory.setTaskType(Const.taskType.VOCATION_TASK_TYPE);
            studentTrajectory.setUserAccountId(vocationTask.getUserAccountId());
            studentTrajectory.setContent(vocationTask.getContent());
            studentTrajectory.save();
        }
        //给学生加分
        if (score > 0) {
            Record record = Redis.use().hget(Const.user.AccountIdInfo, vocationTask.getUserAccountId());
            UserUtil.addScoreForStu(record.getInt("id"), score, Const.addMarkEventType.VOCATION_TASK, vocationTask.getId());
        }
        
        return Ret.ok();
    }

}
